<template>
  <div class="main-container">
    <!-- 条件搜索 -->
    <Condition>
      <div class="condition-item condition-item-5">
        <span class="condition-label">策略名称</span>
        <el-input 
          class="condition-input" 
          v-model="conditionForm.strategyName" 
          placeholder="请输入策略名称" 
          @keyup.enter.native="getList"
          @change="getList"
        />
      </div>
      <div class="condition-item condition-item-5">
        <span class="condition-label">算法平台</span>
        <el-select 
          class="condition-input" 
          v-model="conditionForm.system" 
          placeholder="请选择算法平台"
          clearable
          @change="getList"
        >
          <el-option v-for="(item, index) in systems" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </div>
    </Condition>
    <!-- 数据表格部分 -->
    <div class="data-show">
      <!-- 头部操作按钮部分 -->
      <div class="data-actions">
        <span class="aniTxtBtn action" @click="linkToCreate">新增策略</span>
      </div>
      <!-- 底下表格 -->
      <div class="data-table">
        <el-table border v-loading="conditionForm.loading" :data="datas" stripe show-header>
          <el-table-column label="序号" align="center" type="index" width="100" />
          <el-table-column label="名称" align="center" prop="strategyName"  />
          <el-table-column label="算法平台" align="center" show-overflow-tooltip prop="system" width="100">
            <template #default="{ row }">
              {{ getShow(row.system, 'id', systems, 'name') }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template #default="{ row }">
              {{ getStatus(row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="280" fit>
            <template #default="{ row }">
              <div class="table-actions">
                <button class="aniTxtBtn blue" @click="linkToEdit(row)">编辑</button>
                <button :disabled="row.status !== 0" class="aniTxtBtn main-color" @click="changeStrategyStatues(row)">启用</button>
                <button class="aniTxtBtn red" @click="del(row)">删除</button>
              </div>
            </template>
          </el-table-column>
          <!-- 没有数据时显示 -->
          <template #empty>
            <i class="iconfont icon-wushuju1 data-empty-icon"></i>
            <h3 class="data-empty">暂无数据</h3>
          </template>
        </el-table>
      </div>
      <Pagination 
        v-show="conditionForm.totalRow > 0" 
        :total="conditionForm.totalRow"
        v-model:page="conditionForm.pageNumber"
        v-model:limit="conditionForm.pageSize"
        @pagination="pageChange" 
      />
    </div>
  </div>
</template>
<script setup>
import Condition from '@/components/common/Condition.vue';
import Pagination from '@/components/common/Pagination';
import { ref, computed, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import { api } from '@/utils/status';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as streApi from '@/api/strategy.js';

// ============> data
const systems = api.common.systems
const router = useRouter();
// 搜索条件表单项
const conditionForm = ref({
  flag: false,
  loading: false,
  strategyName: '',
  name: '',
  saveName: '',
  system: null,
  saveSystem: null,
  status: null,
  saveStatus: null,
  // 页条数
  pageSize: 10,
  // 当前页
  pageNumber: 1,
  // 总条数
  totalRow: 0,
  // 总页数
  totalPage: 0
});
const datas = ref([]);

// ============> computed
const getShow = computed(() => {
  return function (v, k, arr, returnKey) {
    let obj = arr.find((item) => item[k] === v);
    let res = obj ? obj[returnKey] : "--";
    return res;
  };
});
const getStatus = computed(() => {
  return function (status){
    return status == 1 ? '已启用' : '已禁用';
  }
})

// ============> methods
// 重置上方的搜索条件
function resetCondition(){
  conditionForm.value.strategyName = conditionForm.value.strategyName != conditionForm.value.saveName ? conditionForm.value.saveName : conditionForm.value.strategyName;
  conditionForm.value.system = conditionForm.value.system != conditionForm.value.saveSystem ? conditionForm.value.saveSystem : conditionForm.value.system;
}
// 设置上方的搜索条件
function setCondition(){
  conditionForm.value.saveName = conditionForm.value.strategyName;
  conditionForm.value.saveSystem = conditionForm.value.system;
}
function getList(){
  if (conditionForm.value.flag){
    resetCondition();
    return;
  }
  conditionForm.value.loading = true;
  const { strategyName, system, pageSize, pageNumber} = conditionForm.value;
  streApi.getStrategyList({ strategyName, system, pageSize, pageNumber})
    .then(res => {
      datas.value = res.records && Array.isArray(res.records) ? res.records : [];
      initDatas();
      setCondition();
      conditionForm.value.pageNumber = +res.pageNumber;
      conditionForm.value.pageSize = +res.pageSize;
      conditionForm.value.totalRow = +res.totalRow;
      conditionForm.value.totalPage = +res.totalPage;
      conditionForm.value.loading= false;
      conditionForm.value.flag = false;
    })
    .catch(err => {
      conditionForm.value.loading = false;
      conditionForm.value.flag = false;
      console.log(err)
      resetCondition();
    })
}
function initDatas(){
  if (Array.isArray(datas.value) && datas.value.length > 0){
    datas.value.forEach(item => {
      item.delFlag = false;
      item.statusFlag = false;
    })
  }
}
// 分页触发事件
function pageChange(e){
  // { page, limit }
  conditionForm.value.pageSize = e.limit;
  conditionForm.value.pageNumber = e.page;
  getList();
}
function del(item){
  if (item.delFlag){
    ElMessage.warning('当前正在执行删除，请稍后重试');
    return;
  }
  ElMessageBox.confirm('您是否确认删除该项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(() => {
      item.delFlag = true;
      streApi.delStrategy({ id: item.id })
        .then(res => {
          ElMessage.success('删除算法成功！');
          item.delFlag = false;
          getList();
        })
        .catch(err => {
          console.log(err)
          item.delFlag = false;
        })
    })
}
// 启用策略
function changeStrategyStatues(item){
  if (item.statusFlag){
    ElMessage.warning('当前正在执行启用策略状态，请稍后');
    return;
  }
  item.statusFlag = true;
  streApi.changeStrategyStatues({id: item.id})
    .then(res => {
      ElMessage.success('启用策略成功');
      getList();
    })
    .catch(err => {
      console.log(err)
    })
    .finally(() => {
      item.statusFlag = false;
    })
}
function linkToCreate(){
  router.push({ name: 'strategyCreate' });
}
function linkToEdit(item){
  router.push({ name: 'strategyCreate', query: { id: item.id} });
}

// onMounted(() => {
//   getList();
// });

onActivated(() => {
  getList();
});
</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.data-add {
  width: 100px;
}
.table-actions {
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 100%;
  height: 100%;
  .action {
    width: 80px;
  }
}
.table-actions-column {
  width: 100%;
  flex-direction: column;
  .actions-column {
    width: 100%;
    display: flex;
    justify-content: space-around;
  }
}
.green {
  color: var(--color-green);
}
.red {
  color: var(--color-red);
  @include red-text-shadow;
}
.blue {
  color: var(--color-text-hover);
  @include blue-text-shadow;
}
.main-color {
  color: var(--color-main);
  @include main-text-shadow;
}
.condition-item-5 {
  width: 46%;
}
</style>